#!/usr/bin/env node
/**
 * 简化的中文 front-matter 搜索测试（不依赖外部服务）
 */

const path = require('path');
const fs = require('fs-extra');
const matter = require('gray-matter');

async function testChineseSupport() {
  console.log('测试中文 Front-matter 支持');
  console.log('==========================\n');
  
  // 测试文档路径
  const chineseDocPath = path.join(__dirname, 'example-docs', 'ai-guide-chinese.md');
  
  try {
    // 读取中文文档
    console.log('1. 读取中文 markdown 文档');
    const content = await fs.readFile(chineseDocPath, 'utf-8');
    console.log('✅ 文件读取成功\n');
    
    // 解析 front-matter
    console.log('2. 解析中文 front-matter');
    const parsed = matter(content);
    console.log('✅ Front-matter 解析成功');
    console.log('解析结果:');
    console.log(JSON.stringify(parsed.data, null, 2));
    console.log('');
    
    // 测试中文字段访问
    console.log('3. 测试中文字段访问');
    console.log(`标题: ${parsed.data.标题}`);
    console.log(`分类: ${parsed.data.分类}`);
    console.log(`标签: ${JSON.stringify(parsed.data.标签)}`);
    console.log(`作者: ${parsed.data.作者}`);
    console.log('✅ 中文字段访问成功\n');
    
    // 测试搜索关键词解析
    console.log('4. 测试搜索关键词解析');
    
    // 模拟 parseSearchTerms 方法
    function parseSearchTerms(keywords) {
      const terms = [];
      const normalizedKeywords = keywords.toLowerCase().trim();
      const spaceSeparated = normalizedKeywords.split(/\s+/).filter(term => term.length > 0);
      
      for (const term of spaceSeparated) {
        if (/[\u4e00-\u9fff]/.test(term)) {
          terms.push(term);
          if (term.length > 1) {
            for (let i = 0; i < term.length; i++) {
              const char = term.charAt(i);
              if (/[\u4e00-\u9fff]/.test(char) && !terms.includes(char)) {
                terms.push(char);
              }
            }
          }
        } else {
          terms.push(term);
        }
      }
      return terms.filter(term => term.length > 0);
    }
    
    const testQueries = ['人工智能', '技术', 'AI 机器学习', '深度学习'];
    for (const query of testQueries) {
      const terms = parseSearchTerms(query);
      console.log(`查询: "${query}" -> 解析词汇: [${terms.join(', ')}]`);
    }
    console.log('✅ 搜索关键词解析测试完成\n');
    
    // 测试匹配逻辑
    console.log('5. 测试匹配逻辑');
    
    function flattenFrontMatter(obj, prefix = '') {
      let result = '';
      for (const [key, value] of Object.entries(obj)) {
        const currentKey = prefix ? `${prefix}.${key}` : key;
        if (value === null || value === undefined) continue;
        
        if (typeof value === 'object' && !Array.isArray(value)) {
          result += flattenFrontMatter(value, currentKey) + ' ';
        } else if (Array.isArray(value)) {
          result += `${currentKey}: ${value.join(' ')} `;
        } else {
          result += `${currentKey}: ${value} `;
        }
      }
      return result;
    }
    
    const searchableText = flattenFrontMatter(parsed.data).toLowerCase();
    console.log('扁平化文本:', searchableText);
    
    const testSearches = ['人工智能', '技术', 'AI', '机器学习'];
    for (const search of testSearches) {
      const found = searchableText.includes(search.toLowerCase());
      console.log(`搜索 "${search}": ${found ? '✅ 找到' : '❌ 未找到'}`);
    }
    
    console.log('\n🎉 中文 Front-matter 支持测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  }
}

if (require.main === module) {
  testChineseSupport().catch(console.error);
}
